import axios from 'axios';
import router from '@/router';
import socket from '../../socket';

export default {
    // 页面跳转
    jumpPage(state, value) {
        router.push({ path: value });
    },
    // 注册
    registry(state, value) {
        console.log(value);
        axios.post(`http://${state.ip}:${state.port}/consumer/registry`, value).then(res => {
            if (res.data.code == 200) {
                router.push({ path: '/login' });
            }
        });
    },
    // 登录成功，记录登录信息
    isLogin(state, value) {
        state.user = value;
        sessionStorage.setItem('loginUser', JSON.stringify(value));
        // this.commit('requestFriend');
    },
    // 查询用户好友信息
    requestFriend(state) {
        console.log("加载好友列表")
        axios.get(`http://${state.ip}:${state.port}/friend/selectFriend/` + state.user.id).then(res => {
            if (state.friendList.length > 1) {
                state.friendList.splice(1)
            }
            state.friendList = state.friendList.concat(res.data.data);
            // 好友列表存在后
            // 初始化socket连接
            socket.initWebSock(state.socketPath + state.user.id + '/' + state.user.loginKey, this._mutations.onmessage[0]);
        })
    },
    // 加载添加好友请求
    loadFriendReqeust(state) {
        axios.get(`http://${state.ip}:${state.port}/friend/loadFriendRequest/` + state.user.id).then(res => {
            if (res.data.code == 200) {
                state.friendRequest = res.data.data;
            }
        })
    },
    // 页面刷新加载数据
    loadData(state) {
        // 获取用户信息
        state.user = JSON.parse(sessionStorage.getItem('loginUser'));
        // 当前聊天的记录
        if (sessionStorage.getItem(state.user.id + 'chatlist')) {
            state.chatList = JSON.parse(sessionStorage.getItem(state.user.id + 'chatlist'));
        }
        // 查询用户好友
        this.commit('requestFriend');
        // 查询好友请求
        this.commit('loadFriendReqeust');
    },
    // 修改选中的好友id
    selectFriend(state, value) {
        state.selectFriendId = value;
        if (state.selectFriendId == -1 && state.friendRequestNum != 0) {
            state.friendRequestNum = 0;
        }
    },
    // 跳转到聊天列表
    toChatList(state) {
        // 在聊天记录中查询是否存在当前好友的聊天
        let chat = state.chatList.find(chat => chat.id == state.selectFriendId);
        if (!chat) {
            let friend = state.friendList.find(friend => friend.id == state.selectFriendId);
            chat = {
                id: friend.id,
                // isRead: true,
                msgNum: 0,
                user: {
                    name: friend.remark,
                    img: friend.img
                },
                messages: []
            }
            state.chatList.unshift(chat);
        }
        state.selectChatId = chat.id;
        router.push({ path: '/chat' })
    },
    // 修改选中的聊天窗口
    selectChat(state, value) {
        state.selectChatId = value;
    },
    // 消息添加到消息列表
    message2chatlist(state, value) {
        // 构建消息对象
        let msg = value

        if (state.showDate) {
            state.showDate = false;
            this.commit('flushDate');

            msg.date = new Date();
            msg.showDate = true;
        } else {
            clearTimeout(state.clearTime);
            this.commit('flushDate');

            msg.date = new Date();
            msg.showDate = false;
        }
        //  查询当前聊天列表中是否存在此对话
        let chat = state.chatList.find(chat => chat.id == msg.chatId);
        if (!chat) {
            // 搜索好友列表
            let friend = state.friendList.find(friend => friend.id == msg.chatId);
            chat = {
                id: friend.id,
                // isRead: true,
                msgNum: 0,
                user: {
                    name: friend.remark,
                    img: friend.img
                },
                messages: []
            }
            state.chatList.unshift(chat);
        }

        // 将消息添加到消息列表
        chat.messages.push(msg);
        // 增加未读消息数，发送通知
        if (!msg.self) {
            chat.msgNum = chat.msgNum + 1;
            state.chatNum = state.chatNum + 1;
            // 通过浏览器发送通知
            this.commit("webNotic", chat);
        }

        // 移动聊天框到第一位
        let chatList = state.chatList;
        for (let i in chatList) {
            if (chat.id == chatList[i].id && i != 0) {
                chatList.splice(i, 1);
                chatList.unshift(chat);
                break;
            }
        }
    },
    // 发送消息
    sendMessage(state, value) {
        let msg = {
            chatId: state.selectChatId,
            content: value,
            self: true
        }
        this.commit('message2chatlist', msg);

        // 将消息发送出去
        msg.from = state.user.id + '';
        msg.to = state.selectChatId + '';

        socket.sendMsg(JSON.stringify(msg));
    },
    // 接收到的消息
    onmessage(state, value) {
        // 解析接收到的消息
        let reMsg = JSON.parse(value);
        // 同意好友申请
        if (reMsg.operation == "newFriend") {
            state.friendList.push(reMsg.friend);
        }
        // 显示好友请求
        if (reMsg.operation == "friendRequest") {
            // 请求数量+1
            state.friendRequestNum = state.friendRequestNum + 1;
            // 刷新好友申请列表
            this.commit('loadFriendReqeust');
            // 结束操作
            return;
        }

        const msg = {
            chatId: reMsg.from,
            content: reMsg.content,
            self: false
        }
        this.commit('message2chatlist', msg);
    },
    // 系统通知
    webNotic(state, value) {
        // 判断消息的长度
        let chat = value;
        let content = `${chat.user.name}给你发了${chat.msgNum}条消息，请查看`

        new Notification(chat.user.name, {
            tag: chat.id,
            body: content, //消息体内容
            icon: "../../assets/img/Wechat.ico" //消息图片
        });
        /* m.onclick = function () {
            //点击当前消息提示框后，跳转到当前页面
            window.focus();
        }; */
    },
    // 退出登录
    logout() {
        sessionStorage.clear();
        socket.onclose();
        // router.push({ path: '/login' });
        location.reload();
    },
    // 清楚聊天记录
    clearChatList(state) {
        state.chatList.splice(0);
        state.selectChatId = -1;
    },
    // 修改搜索值
    changeSearch(state, value) {
        state.search = value;
    },
    // 用于刷新日期显示计时
    flushDate(state) {
        state.clearTime = setTimeout(() => {
            state.showDate = true;
        }, 2 * 60 * 1000);
    },
    // 同意好友请求
    agreeRequest(state, value) {
        axios.get(`http://${state.ip}:${state.port}/friend/agreeRequest/${state.user.id}/${value}`).then(res => {
            if (res.data.code == 200) {
                let friend = state.friendRequest.find(friend => friend.id == value);
                friend.state = 1;
                // 消除红点提示
                state.friendRequestNum = 0;
                // 由于在添加成功时会自动发送一条消息，重新请求好友列表会存在延迟造成程序异常
                // this.commit('requestFriend');
            }
        })
    },
    // 消除消息的圆点提示
    readMsg(state) {
        // 定位到聊天框
        let chat = state.chatList.find(chat => chat.id == state.selectChatId);
        // 总想消息数减去当前消息数
        state.chatNum = state.chatNum - chat.msgNum > 0 ? state.chatNum - chat.msgNum : 0;
        // 未读消息数置0
        chat.msgNum = 0;
    }
}